import { getStaffList } from '@/apis/accessManagement/setup'
import { getStaffInfo } from '@/apis/accessManagement/staff'
import { updateStaffInfo } from '@/apis/accessManagement/staff'
import { forbiddenStaff } from '@/apis/accessManagement/staff'
import { deleteStaff } from '@/apis/accessManagement/staff'
import { getRoleList } from '@/apis/accessManagement/role'
import { resetStaffPwd } from '@/apis/accessManagement/staff'
import ExcelTable from '@/components/exportExcel'
import md5 from 'js-md5'
import {ActionType,ProFormInstance,} from '@ant-design/pro-components'
import {Button, Modal,Drawer,Form,Input,Flex,message,Spin} from 'antd'
import { useRef,useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { observer } from 'mobx-react'
const StaffManage: React.FC = () => {
  useRef<ProFormInstance>()
  useRef<ActionType>()
  const navigate = useNavigate();
  const actionRef = useRef();
  const { TextArea } = Input
  const [messageApi, contextHolder] = message.useMessage()
  const [form] = Form.useForm()
  const [restPwdDrawer, setRestPwdDrawer] = useState(false)
  const [loading, setLoading] = useState(false)
  const [handleId, setHandleId] = useState('')
  const [addStaffAuth, setAddStaffAuth] = useState(false)
  const [editStaffAuth, setEditStaffAuth] = useState(false)

    function showResetPwdDrawer(record:any) {
        // console.log(record)
        setHandleId(record.userID)
        setRestPwdDrawer(true)
    }

    function onClosePwdDrawer() {
        form.resetFields()
        setRestPwdDrawer(false)
    }

    const subChangePwd = async ()=> {
        const oldPwdVal = form.getFieldValue('oldPwdVal');
        const resetPwdVal = form.getFieldValue('resetPwdVal');
        const cfmSetPwdVal = form.getFieldValue('cfmSetPwdVal');
        if (!oldPwdVal) {
            message.error('原密码不能为空');
            return;
        }
        if (!resetPwdVal) {
            message.error('新密码不能为空');
            return;
        }
        if (!cfmSetPwdVal) {
            message.error('请再次输入新密码');
            return;
        }
        if (resetPwdVal !== cfmSetPwdVal) {
            message.error('两次密码输入不一致');
            return;
        }
        try {
            await resetPwdSub(); 
        } catch (error) {
            console.log(error)
        }
    }

    // 提交修改密码
    const resetPwdSub = async () => {
        setLoading(true)
        try {
            const newPwdVal = md5(form.getFieldValue('resetPwdVal'))
            const oldPwdVal = md5(form.getFieldValue('oldPwdVal'))
            const res = await resetStaffPwd({
                userID: handleId,
                currentPassword:oldPwdVal,
                newPassword:newPwdVal,
            });
            if (res || res.data) {
                if (res?.errCode === 0) {
                    message.success('密码修改成功');
                    onClosePwdDrawer()
                } else {
                    message.error(`提交失败: ${res?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // 禁用/解禁员工
    const changeForbidden = async (record:any) => {
        setLoading(true)
        try {
            const response = await forbiddenStaff({
                userId: record.userID,
                status: record.status === 1?2:1,
            });
            if (response || response.data) {
                if (response?.errCode === 0) {
                    message.success('提交成功')
                    actionRef.current?.reloadAndRest()
                } else {
                    message.error(`获取数据失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // 删除员工
    const subDelete = async (record:any) => {
        setLoading(true)
        try {
            const response = await deleteStaff({
                userIds: record.userID,
            });
            if (response || response.data) {
                if (response?.errCode === 0) {
                    message.success('删除成功')
                    actionRef.current?.reloadAndRest()
                } else {
                    message.error(`获取数据失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    useEffect(() => {
        const processAuthData = (authData: any[]) => {
            // 递归
            const traverse = (nodes: any[]) => {
                for (const node of nodes) {
                    if (node.name === '设置' && node.children && node.children.length > 0) {
                        traverse(node.children);
                    }
                    // 检查子节点的 name
                    if (node.name === '新增员工') {
                        setAddStaffAuth(true)
                    }
                    if (node.name === '编辑员工') {
                        setEditStaffAuth(true)
                    }
                    // 如果两个权限都已经找到，提前结束递归
                    if (addStaffAuth && editStaffAuth) {
                        return;
                    }
                    // 如果当前节点有子节点，递归处理子节点
                    if (node.children && node.children.length > 0) {
                        traverse(node.children);
                    }
                }
            };
            traverse(authData);
            return { addStaffAuth, editStaffAuth };
        };
        const checkRouters = setInterval(() => {
            const authData = window.routers?.routes?.[1]?.children || [];
            if (authData.length > 0) {
                clearInterval(checkRouters); // 停止检查
                processAuthData(authData); // 执行逻辑
            }
        }, 200);
        return () => clearInterval(checkRouters); // 清理定时器
    },[])

  return (
    <>
    {contextHolder}
    <Spin spinning={loading} fullscreen size='large'/>
    <ExcelTable
        actionRef={actionRef}
      requestFn={async params => {
        const { pageNum,pageSize,userID='',roleCode='',nickname,status=0,updateBy='', ...newParams } = params; // 处理所需参数名
        const data = await getStaffList({
            ...newParams,
            pagination: {pageNumber:pageNum,showNumber:pageSize}, 
            // normal:1,
            nickName:nickname,
            roleCode:roleCode,
            updateBy:updateBy,
            ...(status ? { status: parseInt(status) } : {}),
            startTime:'',
            endTime:'',
        })
        // adminAccounts
        if (data && data.data) {
            const adminAccounts = data.data.adminAccounts || [];
            const list2 = data.data.list2 || [];
            data.finalData = [...adminAccounts, ...list2];
        }
        return data
      }}
    //   search={false}
      rowSelection={false}
      toolBarRenderFn={() => [
        addStaffAuth && (
            <Button key="add" onClick={
                (record) => {
                  navigate('/setting/enterpriseManage/staffManage/addStaff?state=1')
                }
              }>添加</Button>
        )
      ]}
      columns={[
        {
            title: '序号',
            hideInSearch: true,
            valueType: 'index',
          },
        {
          title: '账号',
          hideInSearch: true,
          dataIndex: 'account',
        },
        {
            title: '昵称',
            dataIndex: 'nickname',
            // hideInSearch: true
        },
        {
            title: 'ID',
            dataIndex: 'userID',
            hideInSearch: true
        },
        {
            title: '角色',
            dataIndex: 'roleName',
            hideInSearch: true
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'select',
            valueEnum: {
                0: '全部',
                1: '正常',
                2: '禁用',
            },
            render: (_, record) => 
                (<span style={{ color: record.status === 1 ? 'green' : record.status === 2 ? 'red' : 'gray' }}>
                {record.status === 1 ? '正常':record.status === 2 ? '禁用':'暂无数据'}
                </span>),
        },
        // {
        //   title: '操作时间',
        //   dataIndex: 'updateTime',
        //   valueType: 'dateRange',
        //   hideInTable: true
        // },
        // {
        //   title: '操作人',
        //   dataIndex: 'updateBy',
        //   hideInSearch: true,
        // },
        {
          title: '操作时间',
          dataIndex: 'updateTime',
          hideInSearch: true,
          valueType: 'dateTime'
        },
        {
          title: '操作',
          key: 'option',
          valueType: 'option',
          render: (_, record) => [
                <a key="password"
                    style={{
                        color: record.userID === 'imAdmin' ? '#ccc' : '#1890ff', 
                        pointerEvents: record.userID === 'imAdmin' ? 'none' : 'auto', 
                        cursor: record.userID === 'imAdmin' ? 'not-allowed' : 'pointer', 
                    }}
                    onClick={() => {showResetPwdDrawer(record)
                    }}>修改密码</a>,
                editStaffAuth && (
                    <a key="update" 
                    style={{
                        color: record.userID === 'imAdmin' ? '#ccc' : '#1890ff', 
                        pointerEvents: record.userID === 'imAdmin' ? 'none' : 'auto', 
                        cursor: record.userID === 'imAdmin' ? 'not-allowed' : 'pointer', 
                    }}
                    onClick={() => {
                        // searchStaff(record)
                        navigate(`/setting/enterpriseManage/staffManage/editStaff?state=2&userId=${record.userID}`)
                    }}>修改信息</a>
                ),
            <a key="disabled" 
                style={{
                    color: record.userID === 'imAdmin' ? '#ccc' : '#1890ff', 
                    pointerEvents: record.userID === 'imAdmin' ? 'none' : 'auto', 
                    cursor: record.userID === 'imAdmin' ? 'not-allowed' : 'pointer', 
                }}
                onClick={() => {
                const text = record.status === 1?'禁用':'解禁'
                setHandleId(record.userID)
                Modal.warning({
                    title: '提示',
                    content: `确定${text}该用户吗?`,
                    okText: '确定',
                    okCancel: true,
                    onOk() {
                        changeForbidden(record);
                    },
                })
            }}>{record.status === 1?'禁用':'解禁'}</a>,
            // <a key="delete"  onClick={() => {
            //     Modal.warning({
            //         title: '提示',
            //         content: '确定删除该用户吗?',
            //         okText: '确定',
            //         okCancel: true,
            //         onOk() {
            //             subDelete(record)
            //         }
            //     });
            // }}>删除</a>,
          ]
        }
      ]}
    />
    <Drawer title="修改密码" onClose={onClosePwdDrawer} open={restPwdDrawer}>
        <Form form={form} onFinish={subChangePwd}>
            <Form.Item label="原密码" name="oldPwdVal" rules={[{required: true, message: '请输入原密码'},{ min: 8, message: '密码至少需要8个字符' },{ max: 20, message: '密码最多20个字符' }]}>
                <Input placeholder="请输入原密码" maxLength={20}/>
            </Form.Item>
            <Form.Item label="设置新密码" name="resetPwdVal" rules={[{required: true, message: '请输入新密码'},{ min: 8, message: '密码至少需要8个字符' },{ max: 20, message: '密码最多20个字符' }]}>
                <Input placeholder="请输入新密码" maxLength={20}/>
            </Form.Item>
            <Form.Item label="确认新密码" name="cfmSetPwdVal" rules={[{required: true, message: '请再次输入新密码'},{ min: 8, message: '密码至少需要8个字符' },{ max: 20, message: '密码最多20个字符' }]}>
                <Input placeholder="请再次输入新密码" maxLength={20}/>
            </Form.Item>
            <Form.Item>
                <Flex justify='center' align='center'>
                    <Button type="primary" htmlType="submit">提交</Button>
                    <Button style={{marginLeft: 10}} onClick={onClosePwdDrawer}>返回</Button>
                </Flex>
            </Form.Item>
        </Form>
    </Drawer>
    </>
  )
}

export default observer(StaffManage)
